package cn.hpclub.server.controller.client.visit;

import java.util.Date;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.controller.client.BaseClientController;
import cn.hpclub.server.exception.BusinessException;
import cn.hpclub.server.model.visit.VisitInfo;
import cn.hpclub.server.restful.API;
import cn.hpclub.server.util.DateKit;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.ObjectUtil;

@API("/visit/client")
public class VisitClientController extends BaseClientController<VisitInfo>{
    private static Logger logger = LoggerFactory.getLogger(VisitClientController.class);

    public void save(){

        JSONObject jsonObject = setResponseObj(ClientApiConstant.ResultCode.FAILED, ClientApiConstant.Msg.FAIL,
                                               ClientApiConstant.Msg.EMPTY);
        VisitInfo obj = new VisitInfo();
        try{
            /**
             * 需前端传递的参数
             */
            String job_number = getPara(VisitInfo.JOB_NUMBER, null);
            String group_number = getPara(VisitInfo.GROUP_NUMBER, null);
            String group_name = getPara(VisitInfo.GROUP_NAME, null);
            String visit_time = DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss");// getPara(VisitInfo.VISIT_TIME,
                                                                                 // null);
            String matter_leader = getPara("isMatterLeadership", null);
            String matter_contact = getPara("isMatterContact", null);
            String common_leader = getPara("isCommonLeadership", null);
            String info_contact = getPara("isInformationContact", null);
            String chief = getPara(VisitInfo.CHIEF, null);
            String location = getPara(VisitInfo.LOCATION, null);
            String longitude = getPara(VisitInfo.LONGITUDE, null);
            String latitude = getPara(VisitInfo.LATITUDE, null);
            String token = getPara(ClientApiConstant.Key.TOKEN);

            logger.debug("----------VisitClientController.save:52行打印接收到的客户端参数—集团名称-----group_name=" + group_name);
            logger.debug("----------VisitClientController.save:53行打印接收到的客户端参数—定位信息-----location=" + location);

            if((StrKit.isBlank(job_number)) || (StrKit.isBlank(group_number)) || (StrKit.isBlank(group_name))
                    || (StrKit.isBlank(matter_leader)) || (StrKit.isBlank(matter_contact))
                    || (StrKit.isBlank(common_leader)) || (StrKit.isBlank(info_contact)) || (StrKit.isBlank(chief))
                    || (StrKit.isBlank(location)) || (StrKit.isBlank(longitude)) || (StrKit.isBlank(latitude))
                    || (StrKit.isBlank(token))){
                throw new IllegalArgumentException("参数非法");
            }
            /**
             * 后台自动获取的参数
             */
            Record userInfoRecord = InterfaceUtil.getuserInfoByToken(token);
            if(ObjectUtil.isEmpty(userInfoRecord)){
                logger.error("not found userInfoRecord<member_org>,the token is " + token);
                throw new BusinessException("无法通过token获取到用户信息，请检查token的合法性");
            }
            String creator = "";
            if(ObjectUtil.isNotEmpty(userInfoRecord) && StrKit.notBlank(String.valueOf(userInfoRecord.getInt("id")))){
                creator = String.valueOf(userInfoRecord.getInt("id"));
            }
            int org_id = userInfoRecord.getInt("org_id");
            Record record = InterfaceUtil.getInfoByOrg(org_id);
            if(ObjectUtil.isEmpty(record)){
                logger.error("not found organization in database,the org_id is " + org_id);
                throw new BusinessException("机构信息不存在");
            }
            String city_id = String.valueOf(record.getInt("city_id"));
            String city = record.getStr("city_name");
            String district = record.getStr("displayName");
            String channel = record.getStr("channel");
            String cm_name = userInfoRecord.getStr("name");
            String cm_phone = userInfoRecord.getStr("user_name");
            String create_time = DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss");
            obj.set(VisitInfo.CM_NAME, cm_name);
            obj.set(VisitInfo.CM_PHONE, cm_phone);
            obj.set(VisitInfo.JOB_NUMBER, job_number);
            obj.set(VisitInfo.CITY_ID, city_id);
            obj.set(VisitInfo.CITY, city);
            obj.set(VisitInfo.DISTRICT, district);
            obj.set(VisitInfo.CHANNEL, channel);
            obj.set(VisitInfo.GROUP_NUMBER, group_number);
            obj.set(VisitInfo.GROUP_NAME, group_name);
            obj.set(VisitInfo.VISIT_TIME, visit_time);
            obj.set(VisitInfo.MATTER_LEADER, matter_leader);
            obj.set(VisitInfo.MATTER_CONTACT, matter_contact);
            obj.set(VisitInfo.COMMON_LEADER, common_leader);
            obj.set(VisitInfo.INFO_CONTACT, info_contact);
            obj.set(VisitInfo.CHIEF, chief);
            obj.set(VisitInfo.LOCATION, location);
            obj.set(VisitInfo.LATITUDE, latitude);
            obj.set(VisitInfo.LONGITUDE, longitude);
            obj.set(VisitInfo.CREATE_TIME, create_time);
            obj.set(VisitInfo.CREATOR, creator);
            obj.set(VisitInfo.CREATE_TIME, create_time);
            if(obj.save()){
                String visitId = String.valueOf(obj.getInt(VisitInfo.ID));
                logger.debug("save visit info success,primary Id=" + visitId);
                jsonObject = setResponseObj(ClientApiConstant.ResultCode.SUCCESS_CODE, "成功",
                                            ClientApiConstant.Msg.EMPTY);
            }
        }
        catch(IllegalArgumentException e){
            logger.error("save visit info failed,error message:" + e.getMessage());
            jsonObject = setResponseObj(ClientApiConstant.ResultCode.PARAM_ERROR, e.getMessage(),
                                        ClientApiConstant.Msg.EMPTY);
        }
        catch(Exception e){
            logger.error("save visit info failed,error message:" + e.getMessage());
            jsonObject = setResponseObj(ClientApiConstant.ResultCode.SERVER_EXCEPTION, e.getMessage(),
                                        ClientApiConstant.Msg.EMPTY);
        }
        renderJson(jsonObject.toString());
    }
}